package com.atwisdom.star.auth.business;

import com.atwisdom.star.common.vo.ActionData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AuthBaseBslService<V, T> {
    /**
     * 构造查询对象
     * @param actionData 参数
     * @return 返回结果
     */
    public QueryWrapper<T> buildQueryWrapper(ActionData<V> actionData) {
        return this.buildQueryWrapper(actionData,true);
    }

    /**
     * 构造查询对象
     * @param actionData 参数
     * @return 返回结果
     */
    public QueryWrapper<T> buildQueryWrapper(ActionData<V> actionData,boolean hasPublished ) {
        String condition = actionData.getCondition();
        String className = actionData.getClassName();
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(actionData.getId()!=null, "id", actionData.getId());
        queryWrapper.eq(StringUtils.isNotBlank(actionData.getType()), "type", actionData.getType());
        queryWrapper.eq(StringUtils.isNotBlank(className), "className", className);
        if(hasPublished){
            queryWrapper.eq("published", "true");
        }
        if(StringUtils.isNotBlank(condition)){
            condition = this.transformOperator(condition);
            queryWrapper.apply(condition);
        }
        queryWrapper.orderByDesc("id");
        return queryWrapper;
    }

    /**
     * 是否有效删除
     * @param actionData 参数
     * @return
     */
    public boolean validActionData(ActionData<V> actionData){
        String condition = actionData.getCondition();
        String className = actionData.getClassName();
        return actionData.getId() != null || !StringUtils.isBlank(actionData.getType()) || !StringUtils.isBlank(className) || !StringUtils.isBlank(condition);
    }


    /**
     * 操作符转换
     *
     * @param condition 转换参数
     */
    public String transformOperator(String condition) {
        Map<String, String> operatorType = this.getOperatorType();
        for (Map.Entry<String, String> entry : operatorType.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            condition = condition.replaceAll(key, value);
        }
        return condition;
    }

    /**
     * 数学操作符与sql操作符映射
     * @return 返回操作数据
     */
    public Map<String, String> getOperatorType() {
        Map<String, String> operatorMap = new HashMap<>();
        operatorMap.put("==", " = ");
        operatorMap.put("!=", " <> ");
        operatorMap.put("≠", " <> ");
        operatorMap.put("≥", " >= ");
        operatorMap.put("≤", " <= ");

        operatorMap.put("&&", " AND ");
        operatorMap.put("\\|\\|", " OR ");
        operatorMap.put("!", " NOT ");
        return operatorMap;
    }
}
